package com.integration.test.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.applet.AppletContext;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * @author admin
 * @description
 * @date 2022/4/12 22:24
 */
@Slf4j
@RestController
@RequestMapping("lock")
public class DistributedLockController {

    @Autowired
    private RedisLockRegistry redisLockRegistry ;
    
    
    @RequestMapping("/redis")
    public void test(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        Lock redisLock = redisLockRegistry.obtain("redis");
        Thread thread1 = getThread(redisLock, String.valueOf(request.getServerPort()));
        thread1.start();
        try {
            thread1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public Thread getThread(Lock redisLock,String name){
       return new Thread(() -> {
            try {
                if (redisLock.tryLock(5, TimeUnit.SECONDS)) {
                    log.info("lock is ready name:{}",name);
                    TimeUnit.SECONDS.sleep(5);
                }
            } catch (InterruptedException e) {
                log.error("obtain lock error {} ,name:{}", e,name);
            } finally {
                redisLock.unlock();
            }
        });
    }
}
